package com.aliyun.oss.service.impl;

import com.aliyun.oss.UserService.WxUserService;
import com.aliyun.oss.mapper.ReportMapper;
import com.aliyun.oss.pojo.Entity.Orders;
import com.aliyun.oss.pojo.Entity.WxUser;
import com.aliyun.oss.pojo.Vo.*;
import com.aliyun.oss.service.ReportService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Orders> implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WxUserService wxUserService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
//        创建集合存储开始到结束日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//        将集合转换为数组
        LocalDate[] dates = dateList.toArray(new LocalDate[0]);
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(Arrays.toString(dates));
        List<BigDecimal> turnoverList = new ArrayList<>();
//        遍历所有日期
        for (LocalDate date : dates) {
//            查询时间是date:00:00到date:23:59,同时status为5（已完成）的订单总数
//            1.获取当前日期的起始和结束
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(LocalDateTime.MAX.toLocalTime());
//            使用mybastic 查询
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 5) // 订单状态为“已完成”
                    .ge("order_time", startOfDay) // 大于等于当天开始时间
                    .le("order_time", endOfDay)   // 小于等于当天结束时间
                    .select("sum(amount)"); // 聚合查询金额总和
            BigDecimal turnover = BigDecimal.ZERO;
            List<Object> resultList = reportMapper.selectObjs(queryWrapper);
            if (resultList != null && !resultList.isEmpty()) {
                Object sumObj = resultList.get(0); // 直接取第一个元素
                if (sumObj != null) {
                    turnover = new BigDecimal(sumObj.toString());
                }
            }
            turnoverList.add(turnover);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < turnoverList.size(); i++) {
            if (i == 0) sb.append("[");
            if (i > 0) {
                sb.append(",");
            }

            sb.append(turnoverList.get(i));
            //            字符串最后添加]
            if (i == turnoverList.size() - 1) {
                sb.append("]");
            }
        }
        String turnoverListStr = sb.toString();
        turnoverReportVO.setTurnoverList(turnoverListStr);
        return turnoverReportVO;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        UserReportVO userReportVO = new UserReportVO();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        LocalDate[] dates = dateList.toArray(new LocalDate[0]);
        userReportVO.setDateList(Arrays.toString(dates));
//        统计新增用户和总用户
        for (LocalDate date : dates) {
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(LocalDateTime.MAX.toLocalTime());
            QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("create_time", startOfDay)
                    .le("create_time", endOfDay);
            int newUser = (int) wxUserService.count(queryWrapper);
            newUserList.add(newUser);
            totalUserList.add((int) wxUserService.count());
        }
        userReportVO.setNewUserList(newUserList.toString());
        userReportVO.setTotalUserList(totalUserList.toString());
        return userReportVO;
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        OrderReportVO orderReportVO = new OrderReportVO();
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalOrderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        LocalDate[] dates = dateList.toArray(new LocalDate[0]);
        orderReportVO.setDateList(Arrays.toString(dates));
        for (LocalDate date : dates) {
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.atTime(LocalDateTime.MAX.toLocalTime());
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("order_time", startOfDay)
                    .le("order_time", endOfDay);
            int totalOrder = (int) count(queryWrapper);
            totalOrderList.add(totalOrder);
            validOrderList.add((int) count(queryWrapper.eq("status", 5)));
        }
        orderReportVO.setTotalOrderList(totalOrderList.toString());
        orderReportVO.setValidOrderList(validOrderList.toString());
        return orderReportVO;
    }

    @Override
    public SelesTop10ReportVO getSelesTop10(LocalDate begin, LocalDate end) {
        SelesTop10ReportVO selesTop10ReportVO = new SelesTop10ReportVO();
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
//        统计时间区间内商品销售 top10
        LocalDateTime startTime = begin.atStartOfDay();
        LocalDateTime endTime = end.atTime(LocalDateTime.MAX.toLocalTime());
        List<Map<String, Object>> selesTop10 = reportMapper.getSelesTop10(startTime, endTime);
        for (Map<String, Object> map : selesTop10) {
            nameList.add((String) map.get("name"));
            // 关键修改：先获取BigDecimal，再通过toString()转换为String
            BigDecimal totalAmount = (BigDecimal) map.get("total_amount"); // 先拿到BigDecimal
            numberList.add(totalAmount.toString()); // 调用toString()转换为字符串
        }
        selesTop10ReportVO.setNameList(nameList.toString());
        selesTop10ReportVO.setNumberList(numberList.toString());
        return selesTop10ReportVO;
    }
}
